package cn.coldleaf.wiki.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 图形验证码
 * @datetime 2023/10/18 上午12:11
 * @user cold
 **/
@Component
public class CaptchaUtil implements InitializingBean {
    private static final int POOL_SIZE = 100;
    private static final int POOL_MIN_SIZE = 10;
    static List<Captcha> captchaPool = Collections.synchronizedList(new ArrayList<>(POOL_SIZE));

    @Override
    public void afterPropertiesSet() throws Exception {
        fullPool();
    }

    public static class Captcha{
        private final String code;
        private final BufferedImage image;
        private Captcha(String code,BufferedImage image){
            this.code = code;
            this.image = image;
        }

        public String getCode() {
            return code;
        }

        public BufferedImage getImage() {
            return image;
        }
    }

    /**
     * 构建验证码
     * @datetime 2023-10-18 11:48:01
     * @user cold
     **/
    public static void genCaptcha(int width,int height){
        int codeLength = 6;
        int fontSize = width/codeLength;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D pen = (Graphics2D) image.getGraphics();
        // 背景色
        pen.setColor(Color.GRAY);
        pen.fillRect(0,0,width,height);

        Color[] colors = new Color[]{
                Color.CYAN,Color.GREEN,Color.MAGENTA,Color.YELLOW,
                Color.ORANGE,Color.PINK,Color.RED
        };
        Random random = new Random(System.currentTimeMillis());

        // 画入干扰线
        int lineCount = random.nextInt(10) + 20;
        for (int i = 0; i < lineCount; i++) {
            pen.setColor(colors[random.nextInt(colors.length)]);
            int x = random.nextInt(width - 1);
            int y = random.nextInt(height -1);
            int x1 = width - random.nextInt(width - 1);
            int y1 = height - random.nextInt(height - 1);
            pen.drawLine(x,y,x1,y1);
        }

        // 画入噪点
        float noiseRate = 0.2f;
        int area = (int) (noiseRate * width * height);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            image.setRGB(x,y,colors[random.nextInt(colors.length)].getRGB());
        }

//        shear(pen,width,height,Color.GRAY,random);
        pen.setFont(new Font(null,Font.BOLD,fontSize));
        String code = StringUtil.randomIgnoreSimilarStr(codeLength);
        for (int i = 0; i < codeLength; i++) {
            pen.setColor(colors[random.nextInt(colors.length)]);
            pen.drawString(String.valueOf(code.charAt(i)),i * fontSize,fontSize);
        }
        pen.dispose();
        captchaPool.add(new Captcha(code,image));
    }

    private static void shear(Graphics g, int w1, int h1, Color color,Random random) {
        shearX(g, w1, h1, color, random);
        shearY(g, w1, h1, color, random);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color,Random random) {

        int period = random.nextInt(2);

        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            g.setColor(color);
            g.drawLine((int) d, i, 0, i);
            g.drawLine((int) d + w1, i, w1, i);
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color,Random random) {

        int period = random.nextInt(40) + 10; // 50;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            g.setColor(color);
            g.drawLine(i, (int) d, i, 0);
            g.drawLine(i, (int) d + h1, i, h1);
        }
    }

    public Captcha getCaptcha(){
        Random random = new Random(System.currentTimeMillis());
        Captcha captcha = captchaPool.remove(random.nextInt(captchaPool.size()));
        // 检查验证码池中验证码数量
        if (captchaPool.size() <= POOL_MIN_SIZE){ // 触发填充机制
            fullPool();
        }
        return captcha;
    }
    public static void fullPool(){
        new Thread(){
            @Override
            public void run() {
                int count = POOL_SIZE - captchaPool.size();
                for (int i = 0; i < count; i++) {
                    genCaptcha(120,30);
                }
            }
        }.start();
    }
}
